// utils/common.js
// ....
// if (process.env.TARO_ENV === 'weapp') {
//   // 微信小程序端执行逻辑
// } else if (process.env.TARO_ENV === 'h5') {
//   // h5 端执行逻辑
// } else if (process.env.TARO_ENV === 'rn') {
//   // react-native 端执行逻辑
// }


export function orderBy(list, key) {
  return list.sort((a, b) => a[key] - b[key]);
}

export function deepTree(list) {
  let newList = [];
  let map = {};

  list.forEach(e => (map[e.id] = e));

  list.forEach(e => {
    let parent = map[e.parentId];

    if (parent) {
      (parent.children || (parent.children = [])).push(e);
    } else {
      if (!e.parentId) {
        newList.push(e);
      }
    }
  });

  const fn = list => {
    list.map(e => {
      if (e.children instanceof Array) {
        e.children = orderBy(e.children, 'orderNum');
        // console.log('e.children',e.children)
        fn(e.children);
      }
    });
  };

  fn(newList);

  return orderBy(newList, 'orderNum');
}

export function revDeepTree(list = []) {
  let d = [];

  const deep = list => {
    list.forEach(e => {
      d.push(e);

      if (e.children && isArray(e.children)) {
        deep(e.children);
      }
    });
  };

  deep(list || []);


  return d;
}


export function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }
  let newObj = obj instanceof Array ? [] : {}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]
    }
  }
  return newObj
}


export function strToDate(dateObj) {
  if (!dateObj) return null
  dateObj = dateObj.replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/(-)/g, '/').replace(/-/g, '/')
  if (dateObj.indexOf(".") > 0) dateObj = dateObj.slice(0, dateObj.indexOf("."))
  // console.log('dateObj', dateObj)
  return dateObj
}


/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, format = 'yyyy-mm-dd') {
  const d = time ? new Date(strToDate(time)) : new Date();
  const t = (i) => {
    return (i < 10 ? '0' : '') + i
  };

  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  const day = d.getDate();
  const hour = d.getHours();
  const minutes = d.getMinutes();
  const seconds = d.getSeconds();
  const weekday = d.getDay();

  return format.replace(/(yy){1,2}|m{1,2}|d{1,2}|h{1,2}|i{1,2}|s{1,2}|w{1,2}/gi, function (r) {
    switch (r.toUpperCase()) {
      case 'YY':
        return ('' + year).substr(2);
      case 'YYYY':
        return year;
      case 'M':
        return month;
      case 'MM':
        return t(month);
      case 'D':
        return day;
      case 'DD':
        return t(day);
      case 'H':
        return hour;
      case 'HH':
        return t(hour);
      case 'I':
        return minutes;
      case 'II':
        return t(minutes);
      case 'S':
        return seconds;
      case 'SS':
        return t(seconds);
      case 'W':
        return `星期${['日', '一', '二', '三', '四', '五', '六'][weekday]}`;
      case 'WW':
        return ['Sunday', 'Monday', 'TuesDay', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][weekday];
    }
  });
}

export function moneyFormat(val) {
  val = parseFloat(val)
  val = val.toString().replace(/\$|\,/g, '')
  if (isNaN(val)) {
    val = '0'
  }
  // eslint-disable-next-line eqeqeq
  const sign = (val == (val = Math.abs(val)))
  val = Math.floor(val * 100 + 0.50000000001)
  let cents = val % 100
  val = Math.floor(val / 100).toString()
  if (cents < 10) {
    cents = '0' + cents
  }
  for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
    val = val.substring(0, val.length - (4 * i + 3)) + ',' + val.substring(val.length - (4 * i + 3))
  }

  return (((sign) ? '' : '-') + val + '.' + cents)
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/** * 自定义函数名：formatZero
 * @param num： 需要补零的数值
 * @param len： 补零后的总位数
 */
export function formatZero(num, len) {
  // if(String(num).length > len) return num;
  // return (Array(len).join(0) + num).slice(-len);
  return (num / Math.pow(10, len)).toFixed(len).substr(2)
}

/**
 * 将秒转换为 分:秒
 * s int 秒数
 */
export function s_to_hs(s) {
  s = Math.floor(s)
  //计算分钟
  //算法：将秒数除以60，然后下舍入，既得到分钟数
  var h;
  h = Math.floor(s / 60);
  //计算秒
  //算法：取得秒%60的余数，既得到秒数
  s = s % 60;
  //将变量转换为字符串
  h += '';
  s += '';
  //如果只有一位数，前面增加一个0
  h = (h.length == 1) ? '0' + h : h;
  s = (s.length == 1) ? '0' + s : s;
  return h + ':' + s;
}
